package com.zd.novel.service.impl;

import com.zd.common.pojo.Author;
import com.zd.common.pojo.Chapter;
import com.zd.common.pojo.Novel;
import com.zd.common.pojo.User;
import com.zd.novel.mapper.NovelMapper;
import com.zd.novel.service.NovelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



import java.util.Date;
import java.util.Random;

@Service
public class NovelServiceImpl implements NovelService {
    @Autowired
    private NovelMapper novelMapper;

    Date date=new Date();

    /**
     *管理员新建小说接口
     * 前端传入.小说名,作家id,分类id
     * 随即判断小说名是否合法/null,通过则执行下一步
     * 业务层查询书名是否已存在,存在则返回错误给前端
     * 不存在则执行判断用户的角色是否是作者/否则新建失败/是则下一步业务
     *随后写入状态:初始小说创建未有章节状态为:未上架=3,1=上架连载,2=上架完结,3=未上架,4=下架未完结
     */
   @Transactional
    public String insertNovel(Novel novel, Integer id) {
        String msg="";//返回null时则无
        //1.查询数据库小说名是否存在
        String name = novel.getNovelName();
        System.out.println(name);

        Novel novelDB = novelMapper.selectName(name);

        System.out.println("NoveldB:"+novelDB);

        User user=novelMapper.selectUserByid(id);
        if (user==null){
            msg="没有该用户,请确认该用户是否存在!";
            return msg;
        }
        if (novelDB==null){
            Integer authorId = novel.getAuthorId();

            System.out.println("测试ID:"+authorId);

            Author author=novelMapper.selecctauthorById(authorId);

            System.out.println("测试:"+ author);
            if (author==null){
                msg="你不是作家,请先申请成为作家";
                return msg;
            }

            novel.setStatus(3);
            novel.setCreated(date);
            System.out.println(novel);

            novelMapper.insertNovel(novel);
            System.out.println("入库后的测试:"+novel);

            msg="新增成功,新增的书名为:"+novel.getNovelName();
            return msg;
        }
        msg="书名重复,请更改您的书名";
        return msg;
    }





    /**
     * 接收到章节对象:chapter,书籍ID
     * 做出成功则入库,失败则事务回滚
     * 入库说明:除了新增进章节表外,还要通过内容或者小说名查出章节ID,随后把章节ID以及小说ID一同写入关联表:zd_novel_chapter
     * @param chapter
     * @param novelId
     * @return
     */
    public String insertChapert(Chapter chapter, Integer novelId) {
        Random random = new Random(999999999);
        System.out.println(random);

        return null;
    }


}





